#include "ghToolkit.h"


int _ghTPIXEL ( SDL_Surface *sdlsTemp, int iX, int iY );


        /**\brief Inicia los servicios del toolkit. */
        /** Inicia la librería SDL y inicializa openGL. Se pasa como argumento, el modo que se usara para iniciarse. */
        void ghToolkit::system::init( int iMode ){
            startclock      = SDL_GetTicks();

            switch ( iMode ) {
                case 1:
                    if ( SDL_Init(SDL_INIT_EVERYTHING) != 0 ) {
                        cout << "No se ha podido iniciar SDL." << endl;
                        atexit(TTF_Quit);
                    }
                    if(Mix_OpenAudio(22050, AUDIO_S16, 2, 4096)) {
                        printf("Unable to open audio!\n");
                        exit(1);
                        }

                    if(TTF_Init() != 0) {
                        TTF_GetError();
                        atexit(TTF_Quit);
                    }

                    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

                    break;
                default:
                    cout << "No se ha podido iniciar." << endl;
                    exit(0);
                    break;
            }
        }
        void ghToolkit::system::title ( const char *chTitle ) {
             SDL_WM_SetCaption( chTitle , NULL );
        }


        int ghToolkit::system::fps( void ) {
            deltaclock = SDL_GetTicks() - startclock;
            startclock = SDL_GetTicks();

            if ( deltaclock != 0 )
                currentFPS = 1000 / deltaclock;
        return currentFPS;
        }
        /**\brief Metodo de creacion de una ventana nueva. */
        /** Crea una ventana con el ancho, alto y profundidad de pixels pasados en los argumentos. Tambien se pasa una cadena de texto, con el titulo que llevara la ventana.*/
        void ghToolkit::system::window ( int iWidth, int iHeight, int iBpp ){

            sdlsWindow = SDL_SetVideoMode( iWidth, iHeight, iBpp , SDL_OPENGL  );
            if ( !sdlsWindow ) {
                cout << "Error" << endl;
            }


            glEnable(GL_TEXTURE_2D);
            glShadeModel(GL_SMOOTH);
            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
            glClearDepth(1.0f);

            glEnable(GL_DEPTH_TEST);
            glDepthFunc(GL_LEQUAL);
            glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
            glHint(GL_POINT_SMOOTH_HINT,GL_NICEST);
            glEnable(GL_BLEND);
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

            glViewport(0, 0, iWidth, iHeight);
            glMatrixMode(GL_PROJECTION);
            glLoadIdentity();
            glOrtho( 0, iWidth, iHeight, 0, -1, 1 );
            glMatrixMode(GL_MODELVIEW);
            glLoadIdentity();
        }

        /**\brief Rellena el fondo de pantalla */
        /** Rellena la pantalla con el color pasado por argumento. */
        void ghToolkit::system::fill( float fR, float fG, float fB ){
            glClearColor( fR, fG, fB, 0 );
            glClear( GL_COLOR_BUFFER_BIT );
        }

        /**\brief Limpia la pantalla */
        /** Borra el contenido de la pantalla */
        void ghToolkit::system::clear( void ){
        	glClearColor( 0 ,0, 0, 0 );
            glClear( GL_COLOR_BUFFER_BIT );
        }

        /**\brief Intercambia los buffers de pantalla */
        /** */
        void ghToolkit::system::flip( void ){
            glFlush();
            SDL_GL_SwapBuffers();
        }

        /**\brief Crea un retraso */
        /** Crea un retraso de ( iseconds ) segundos.*/
        void ghToolkit::system::delay( int iSeconds ){
                SDL_Delay ( iSeconds * 1000 );
        }

        /**\brief Muestra o oculta el raton */
        /**Se le pasa por argumento el valor 0 si se quiere ocultar el raton, 1 si se quiere mostrar. Por defecto es 0.*/
        void ghToolkit::motion::setMouse( bool bShow ){

        switch ( bShow ) {
            case 1:
                SDL_ShowCursor (SDL_ENABLE);
                break;
            default:
                SDL_ShowCursor (SDL_DISABLE);
                break;
            }
        }

        /**\brief Se activa en busqueda de algun evento.*/
        /** Este metodo se llama para revisar todos los eventos que puedan suceder. Estan relacionados directamente el sistema de teclado, raton y joypad.*/
        int ghToolkit::motion::getEvents ( void ){

            mX = sdleHandler.motion.x;
            mY = sdleHandler.motion.y;

            while ( SDL_PollEvent(&sdleHandler) || SDL_PollEvent(&sdleHandler) ) {
                if ( sdleHandler.type == SDL_QUIT ) {
                    Mix_CloseAudio();
                    atexit(SDL_Quit);
                    return iReturnsignal = 666;
                }

                if( sdleHandler.type == SDL_MOUSEBUTTONDOWN ) {
                    if( sdleHandler.button.button == SDL_BUTTON_LEFT ) {
                        iReturnsignal = 138;
                    }
                    if( sdleHandler.button.button == SDL_BUTTON_MIDDLE ) {
                        iReturnsignal = 139;
                    }
                    if( sdleHandler.button.button == SDL_BUTTON_RIGHT ) {
                        iReturnsignal = 140;
                    }
                }

                if ( sdleHandler.key.keysym.sym == SDLK_ESCAPE )   { iReturnsignal = 1; }
                if ( sdleHandler.key.keysym.sym == SDLK_UP )       { iReturnsignal = 91; }
                if ( sdleHandler.key.keysym.sym == SDLK_DOWN )     { iReturnsignal = 92; }
                if ( sdleHandler.key.keysym.sym == SDLK_LEFT )     { iReturnsignal = 94; }
                if ( sdleHandler.key.keysym.sym == SDLK_RIGHT )    { iReturnsignal = 93; }
                if ( sdleHandler.key.keysym.sym == SDLK_a )        { iReturnsignal = 47; }
                if ( sdleHandler.key.keysym.sym == SDLK_b )        { iReturnsignal = 48; }
                if ( sdleHandler.key.keysym.sym == SDLK_c )        { iReturnsignal = 49; }
                if ( sdleHandler.key.keysym.sym == SDLK_d )        { iReturnsignal = 50; }
                if ( sdleHandler.key.keysym.sym == SDLK_e )        { iReturnsignal = 51; }
                if ( sdleHandler.key.keysym.sym == SDLK_f )        { iReturnsignal = 52; }
                if ( sdleHandler.key.keysym.sym == SDLK_g )        { iReturnsignal = 53; }
                if ( sdleHandler.key.keysym.sym == SDLK_h )        { iReturnsignal = 54; }
                if ( sdleHandler.key.keysym.sym == SDLK_i )        { iReturnsignal = 55; }
                if ( sdleHandler.key.keysym.sym == SDLK_j )        { iReturnsignal = 56; }
                if ( sdleHandler.key.keysym.sym == SDLK_k )        { iReturnsignal = 57; }
                if ( sdleHandler.key.keysym.sym == SDLK_l )        { iReturnsignal = 58; }
                if ( sdleHandler.key.keysym.sym == SDLK_m )        { iReturnsignal = 59; }
                if ( sdleHandler.key.keysym.sym == SDLK_n )        { iReturnsignal = 60; }
                if ( sdleHandler.key.keysym.sym == SDLK_o )        { iReturnsignal = 61; }
                if ( sdleHandler.key.keysym.sym == SDLK_p )        { iReturnsignal = 62; }
                if ( sdleHandler.key.keysym.sym == SDLK_q )        { iReturnsignal = 63; }
                if ( sdleHandler.key.keysym.sym == SDLK_r )        { iReturnsignal = 64; }
                if ( sdleHandler.key.keysym.sym == SDLK_s )        { iReturnsignal = 65; }
                if ( sdleHandler.key.keysym.sym == SDLK_t )        { iReturnsignal = 66; }
                if ( sdleHandler.key.keysym.sym == SDLK_u )        { iReturnsignal = 67; }
                if ( sdleHandler.key.keysym.sym == SDLK_v )        { iReturnsignal = 68; }
                if ( sdleHandler.key.keysym.sym == SDLK_w )        { iReturnsignal = 69; }
                if ( sdleHandler.key.keysym.sym == SDLK_x )        { iReturnsignal = 70; }
                if ( sdleHandler.key.keysym.sym == SDLK_y )        { iReturnsignal = 71; }
                if ( sdleHandler.key.keysym.sym == SDLK_z )        { iReturnsignal = 72; }

            }
            if ( sdleHandler.type == SDL_KEYUP  || sdleHandler.type == SDL_MOUSEBUTTONUP  ) { iReturnsignal = 0; }
            fflush(stdin);
            return iReturnsignal;
        }

        /**\brief Devuelve la posicion X del raton */
        /** */
        int ghToolkit::motion::getMouseX( void ){
            return mX;
        }

        /**\brief Devuelve la posicion Y del raton */
        /** */
        int ghToolkit::motion::getMouseY( void ){
            return mY;
        }

        /**\brief Carga una imagen en la entidad */
        /** */
        void ghToolkit::entity2D::load   ( const char *chSprite ){
            if (  (sdlsSprite = IMG_Load ( chSprite )) ) {
                spX=0;
                spY=0;
                spW=sdlsSprite->w;
                spH=sdlsSprite->h;
                spA=0;
                spS=1;
                spP=1;
                spcR = 1;
                spcG = 1;
                spcB = 1;

                nOfColors = sdlsSprite->format->BytesPerPixel;
                if (nOfColors == 4) {
                    if (sdlsSprite->format->Rmask == 0x000000ff)
                        texture_format = GL_RGBA;
                            else
                                texture_format = GL_BGRA;
                                    } else if (nOfColors == 3) {
                                        if (sdlsSprite->format->Rmask == 0x000000ff)
                                            texture_format = GL_RGB;
                                                else
                                                    texture_format = GL_BGR;
                                                        } else {
                                                            printf("warning: the image is not truecolor..  this will probably break\n");
                }

                glGenTextures( 1, &uiGSprite );
                glBindTexture( GL_TEXTURE_2D, uiGSprite );
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
                glTexImage2D( GL_TEXTURE_2D, 0, nOfColors, sdlsSprite->w, sdlsSprite->h, 0,
                            texture_format, GL_UNSIGNED_BYTE, sdlsSprite->pixels );
                            glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
                } else {
                cout << "Could't load the image file" <<endl;
                exit(0);
            }
        }

        void ghToolkit::entity2D::color ( float fR, float fG, float fB){
            spcR = fR;
            spcG = fG;
            spcB = fB;
        }

        /**\brief Dibuja la entidad en la pantalla.*/
        /** */
        void ghToolkit::entity2D::draw   ( int iX, int iY ){
            spX = iX;
            spY = iY;

            glBindTexture( GL_TEXTURE_2D,uiGSprite );
            glLoadIdentity();

            glColor4f( spcR , spcG, spcB, spP );
            glTranslatef ( spX  ,spY  ,0 );
            glScalef( spS , spS, 0);

            glRotatef( spA ,0.0f,0.0f,1.0);
            glTranslatef ( -spX - sdlsSprite->w /2 ,-spY - sdlsSprite->h /2,0 );

            glBegin( GL_QUADS );
            // Top-left vertex (corner)
            glTexCoord2i( 0, 0 );
            glVertex3f( spX, spY, 0 );

            // Bottom-left vertex (corner)
            glTexCoord2i( 1, 0 );
            glVertex3f( spX + sdlsSprite->w, spY, 0 );

            // Bottom-right vertex (corner)
            glTexCoord2i( 1, 1 );
            glVertex3f( spX + sdlsSprite->w, spY + sdlsSprite->h, 0 );

            // Top-right vertex (corner)
            glTexCoord2i( 0, 1 );
            glVertex3f( spX, spY + sdlsSprite->h, 0 );
        glEnd();

        }

        /**\brief Dibuja la entidad en la pantalla.*/
        /** */
        void ghToolkit::entity2D::draw   ( gh2iVector2D vect ){
            spX = vect.x;
            spY = vect.y;

            glBindTexture( GL_TEXTURE_2D,uiGSprite );
            glLoadIdentity();

            glColor4f( spcR , spcG, spcB, spP );
            glTranslatef ( spX  ,spY  ,0 );
            glScalef( spS , spS, 0);

            glRotatef( spA ,0.0f,0.0f,1.0);
            glTranslatef ( -spX - sdlsSprite->w /2 ,-spY - sdlsSprite->h /2,0 );

            glBegin( GL_QUADS );
            // Top-left vertex (corner)
            glTexCoord2i( 0, 0 );
            glVertex3f( spX, spY, 0 );

            // Bottom-left vertex (corner)
            glTexCoord2i( 1, 0 );
            glVertex3f( spX + sdlsSprite->w, spY, 0 );

            // Bottom-right vertex (corner)
            glTexCoord2i( 1, 1 );
            glVertex3f( spX + sdlsSprite->w, spY + sdlsSprite->h, 0 );

            // Top-right vertex (corner)
            glTexCoord2i( 0, 1 );
            glVertex3f( spX, spY + sdlsSprite->h, 0 );
        glEnd();
        }


        /**\brief Define la escala de la entidad. Los valores son %.*/
        /** El tamaño real de la imagen se mostrara si este valor es 100 ( 100% ), a la mitad si es 50 ( 50% ) etc...*/
        void ghToolkit::entity2D::scale  ( float fScale ){
            spS = fScale*.01;
        }

        /**\brief Define el angulo de la entidad. Los valores son de 0 a 360.*/
        /** */
        void ghToolkit::entity2D::angle  ( float fAngle ){
            spA = fAngle;
        }

        /**\brief Define la opacidad de la entidad. Los valores son de 0f a 100f. */
        /** */
        void ghToolkit::entity2D::alpha  ( float fAlpha ){
            spP = fAlpha*.01;
        }

        /**\brief */
        /** */
        SDL_Surface *ghToolkit::entity2D::getSprite  ( void ){
            return sdlsSprite;
        }

        int ghToolkit::entity2D::getX ( void ){
            return spX;
        }

        int ghToolkit::entity2D::getY ( void ){
            return spY;
        }

        int ghToolkit::entity2D::getWidth ( void ){
            return spW;
        }

        int ghToolkit::entity2D::getHeight ( void ){
            return spH;
        }

        int ghToolkit::entity2D::getScale ( void ){
            return spS;
        }

        int ghToolkit::entity2D::getAngle ( void ){
            return spA;
        }

        int ghToolkit::entity2D::getAlpha ( void ){
            return spP;
        }
        /**\brief Devuelve 1 si existe una colision entre las dos entidades 2D.*/
        /** Con el ultimo argumento definimos el tipo de deteccion. Si vale 0, la colision
            sera por caja, mientras que si vale 1, sera colision por pixel.*/
        int ghToolkit::event::collision ( ghToolkit::entity2D obj1,  ghToolkit::entity2D obj2 ){
            SDL_Surface *as = obj1.getSprite();
            SDL_Surface *bs = obj2.getSprite();
            int ax = obj1.getX();
            int ay = obj1.getY();
            int bx = obj2.getX();
            int by = obj2.getY();
            int skip = 1;

            int ax1 = ax + as->w - 1;
            int ay1 = ay + as->h - 1;

            /*b - bottom right co-ordinates in world space*/
            int bx1 = bx + bs->w - 1;
            int by1 = by + bs->h - 1;

            /*check if bounding boxes intersect*/
            if((bx1 < ax) || (ax1 < bx))
                return 0;
            if((by1 < ay) || (ay1 < by))
                return 0;

            int xstart = ghCOLLIDE_MIN(ax,bx);
            int xend = ghCOLLIDE_MIN(ax1,bx1);

            int ystart = ghCOLLIDE_MIN(ay,by);
            int yend = ghCOLLIDE_MIN(ay1,by1);

            for(int y = ystart ; y <= yend ; y += skip) {
                for(int x = xstart ; x <= xend ; x += skip) {
                /*compute offsets for surface
                before pass to TransparentPixel test
                if(!ghTransparentPixel(as , x-ax , y-ay) && !ghTransparentPixel(bs , x-bx , y-by)){
               return 1;
                }*/
                    if(!_ghTPIXEL(as , x-ax , y-ay) && !_ghTPIXEL(bs , x-bx , y-by)){
                        return 1;
                    }
                }
            }
            SDL_FreeSurface ( as );
            SDL_FreeSurface ( bs );
            return 0;
        }

        /**\brief Carga una fuente TTF.*/
        /** */
        void ghToolkit::text::load   ( const char *chfont ){
            ttfFont = TTF_OpenFont ( chfont, 12 );

        }

        /**\brief Define el color del texto.*/
        /** */
        void ghToolkit::text::color  ( int iR, int iG, int iB ){
            colorText.r = iR;
            colorText.g = iG;
            colorText.b = iB;
            }

        /**\brief Define el tamaño del texto.*/
        /** */
        void ghToolkit::text::scale  ( int iscale ){}

        /**\brief Define el angulo del texto.*/
        /** */
        void ghToolkit::text::angle  ( int iangle ){}

        /**\brief Define la opacidad del texto.*/
        /** */
        void ghToolkit::text::alpha  ( int ialpha ){}

        /**\brief Escribe una cadena de caracteres.*/
        /** */
        void ghToolkit::text::write  ( const char *text, int iX, int iY ){
            SDL_Surface * initial;
            int w,h;

            GLuint texture;
             colorText.r = 255;
            colorText.g = 255;
            colorText.b = 255;

            initial = TTF_RenderText_Blended( ttfFont, text, colorText );
            w = initial->w;
            h = initial->h;

			/* Tell GL about our new texture */
            glGenTextures(1, &texture);
            glBindTexture(GL_TEXTURE_2D, texture);
            glTexImage2D(GL_TEXTURE_2D, 0, 4, w, h, 0, GL_BGRA,
			GL_UNSIGNED_BYTE, initial->pixels );

            /* GL_NEAREST looks horrible, if scaled... */
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

            /* prepare to render our texture */
            glEnable(GL_TEXTURE_2D);
            glBindTexture(GL_TEXTURE_2D, texture);
            glColor3f(1.0f, 1.0f, 1.0f);

            /* Draw a quad at location */
            glBegin(GL_QUADS);
                /* Recall that the origin is in the lower-left corner
                That is why the TexCoords specify different corners
            than the Vertex coors seem to. */

            // Top-left vertex (corner)
            glTexCoord2i( 0, 0 );
            glVertex3f( iX, iY, 0 );

            // Bottom-left vertex (corner)
            glTexCoord2i( 1, 0 );
            glVertex3f( iX + w, iY, 0 );

            // Bottom-right vertex (corner)
            glTexCoord2i( 1, 1 );
            glVertex3f( iX + w, iY + h, 0 );

            // Top-right vertex (corner)
            glTexCoord2i( 0, 1 );
            glVertex3f( iX, iY + h, 0 );


	glEnd();

	/* Bad things happen if we delete the texture before it finishes */
	glFinish();


	/* Clean up */
            SDL_FreeSurface(initial);
            glDeleteTextures(1, &texture);


        }

        /**\brief Escribe un valor numerico.*/
        /** */
        void ghToolkit::text::write  ( int ivar , int iX, int iY ){
                 SDL_Surface * initial;
            int w,h;
            char text[255];
            sprintf( text, "%d", ivar );
            GLuint texture;
             colorText.r = 255;
            colorText.g = 255;
            colorText.b = 255;

            initial = TTF_RenderText_Blended( ttfFont, text, colorText );
            w = initial->w;
            h = initial->h;

			/* Tell GL about our new texture */
            glGenTextures(1, &texture);
            glBindTexture(GL_TEXTURE_2D, texture);
            glTexImage2D(GL_TEXTURE_2D, 0, 4, w, h, 0, GL_BGRA,
			GL_UNSIGNED_BYTE, initial->pixels );

            /* GL_NEAREST looks horrible, if scaled... */
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

            /* prepare to render our texture */
            glEnable(GL_TEXTURE_2D);
            glBindTexture(GL_TEXTURE_2D, texture);
            glColor3f(1.0f, 1.0f, 1.0f);

            /* Draw a quad at location */
            glBegin(GL_QUADS);
                /* Recall that the origin is in the lower-left corner
                That is why the TexCoords specify different corners
            than the Vertex coors seem to. */

            // Top-left vertex (corner)
            glTexCoord2i( 0, 0 );
            glVertex3f( iX, iY, 0 );

            // Bottom-left vertex (corner)
            glTexCoord2i( 1, 0 );
            glVertex3f( iX + w, iY, 0 );

            // Bottom-right vertex (corner)
            glTexCoord2i( 1, 1 );
            glVertex3f( iX + w, iY + h, 0 );

            // Top-right vertex (corner)
            glTexCoord2i( 0, 1 );
            glVertex3f( iX, iY + h, 0 );


	glEnd();

	/* Bad things happen if we delete the texture before it finishes */
	glFinish();


	/* Clean up */
            SDL_FreeSurface(initial);
            glDeleteTextures(1, &texture);

        }

        /**\brief Carga un sonido en memoria.*/
        /** */
        void ghToolkit::sound::load   ( const char *chsound ){
             mmMusic = Mix_LoadMUS(chsound);

            }

        /**\brief Carga un sonido en memoria.*/
        /** */
        void ghToolkit::sound::loadfx   ( const char *chsoundfx ){
            iAudioChannels = -1;
             mmFx = Mix_LoadWAV(chsoundfx);

            }

        /**\brief Reproduce el sonido.*/
        /** Con imode decidimos si sonara solo una vez ( 0 ) o si sonara en loop ( 1 ).*/
        void ghToolkit::sound::play   ( int imode ){
            Mix_PlayMusic( mmMusic, imode );
            }

        /**\brief Reproduce el sonido.*/
        /** Con imode decidimos si sonara solo una vez ( 0 ) o si sonara en loop ( 1 ).*/
        void ghToolkit::sound::playfx   (  ){
            if(iAudioChannels < 0) {
                iAudioChannels = Mix_PlayChannel(-1, mmFx, 0);
                } else {
                Mix_HaltChannel(iAudioChannels);
                iAudioChannels = -1;
            }
     //   SDL_Delay(5000);
        }

        /**\brief Pausa un sonido.*/
        /** */
        void ghToolkit::sound::pause  ( void ){
            Mix_PauseMusic();
        }
 /**\brief Pausa un sonido.*/
        /** */
        void ghToolkit::sound::resume  ( void ){
            Mix_ResumeMusic();
        }

        /**\brief Para un sonido.*/
        /** */
        void ghToolkit::sound::stop   ( void ){
            Mix_HaltMusic();
        }


        /**\brief Establece los fx.*/
        /** */
        void ghToolkit::fx::shadow ( ghToolkit::entity2D obj, int iDistance, int iPositionLigth ) {
        obj.alpha ( 10 );
        obj.color (0,0,0);

        switch ( iPositionLigth ) {
            case 0: // 100 000 000
                obj.draw ( obj.getX()-iDistance, obj.getY()-iDistance );
                break;
            case 1: // 010 000 000
                obj.draw ( obj.getX(), obj.getY()-iDistance );
                break;
            case 2: // 001 000 000
                obj.draw ( obj.getX()+iDistance, obj.getY()-iDistance );
                break;
            case 3: // 000 100 000
                obj.draw ( obj.getX()-iDistance, obj.getY() );
                break;
            case 4: // 000 010 000
                obj.scale ( 130 );
                obj.draw ( obj.getX(), obj.getY() );
                break;
            case 5: // 000 001 000
                obj.draw ( obj.getX()+iDistance, obj.getY() );
                break;
            case 6: // 000 000 100
                obj.draw ( obj.getX()-iDistance, obj.getY()+iDistance );
                break;
            case 7: // 000 000 010
                obj.draw ( obj.getX(), obj.getY()+iDistance );
                break;
            case 8: // 000 000 001
                obj.draw ( obj.getX()+iDistance, obj.getY()+iDistance );
                break;
    }
}

        int _ghTPIXEL ( SDL_Surface *sdlsTemp, int iX, int iY ){

            if(SDL_MUSTLOCK(sdlsTemp))
            SDL_LockSurface(sdlsTemp);

            int bpp = sdlsTemp->format->BytesPerPixel;
            /*here p is the address to the pixel we want to retrieve*/
            Uint8 *p = (Uint8 *)sdlsTemp->pixels + iY * sdlsTemp->pitch + iX * bpp;

            Uint32 pixelcolor;

            switch(bpp) {
                case(1):
                    pixelcolor = *p;
                break;

                case(2):
                    pixelcolor = *(Uint16 *)p;
                break;

                case(3):
                    if(SDL_BYTEORDER == SDL_BIG_ENDIAN)
                    pixelcolor = p[0] << 16 | p[1] << 8 | p[2];
                        else
                    pixelcolor = p[0] | p[1] << 8 | p[2] << 16;
                break;

                case(4):
                    pixelcolor = *(Uint32 *)p;
                break;
            }

            if(SDL_MUSTLOCK(sdlsTemp))
            SDL_UnlockSurface(sdlsTemp);

            return (pixelcolor == sdlsTemp->format->colorkey);
        }

